import type { Claims } from "@/types/claims";

const get = (key: string) => {
	const s = localStorage.getItem(key);
	if (s == null) return null;
	try {
		return JSON.parse(s);
	} catch {
		console.error(`JSON parse error: ${s}`);
		return null;
	}
};

const set = (key: string, data: unknown) => {
	localStorage.setItem(key, JSON.stringify(data));
};

const remove = (key: string) => {
	localStorage.removeItem(key);
};

const sessionGet = (key: string) => {
	const s = sessionStorage.getItem(key);
	if (s == null) return null;
	try {
		return JSON.parse(s);
	} catch {
		console.error(`JSON parse error: ${s}`);
		return null;
	}
};

const sessionSet = (key: string, data: unknown) => {
	sessionStorage.setItem(key, JSON.stringify(data));
};

const sessionRemove = (key: string) => {
	sessionStorage.removeItem(key);
};

const claimsKey = "claims";

const getClaims = () => get(claimsKey) as Claims | null;

const setClaims = (claims: Claims) => set(claimsKey, claims);

const removeClaims = () => remove(claimsKey);

export default {
	get,
	set,
	remove,
	sessionGet,
	sessionSet,
	sessionRemove,
	getClaims,
	setClaims,
	removeClaims,
};
